//
//  SetHomeTabController.m
//  万物记
//
//  Created by Ajen on 2019/6/20.
//  Copyright © 2019 Ajen. All rights reserved.
//

#import "SetHomeTabController.h"
#import "EditHomeTabCell.h"
#import "NewChangeNicknameAlertView.h"
@interface SetHomeTabController ()<UITableViewDelegate,UITableViewDataSource>{
    UIBarButtonItem * rightItem;
    UIBarButtonItem * rightItem2;
    NSMutableArray * muArray;
    BOOL isEdit;
}
@property(nonatomic,strong)UITableView * tableView;

@end

@implementation SetHomeTabController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor colorWithAjenHex:0x7a7374 alpha:1];
    self.navigationController.navigationBar.barTintColor = [UIColor whiteColor];
    self.edgesForExtendedLayout = UIRectEdgeNone;
    
    UILabel * titleLabel = [UILabel new];
    titleLabel.aj_Text(@"栏目管理").aj_textColorHexStr(@"#2d2e36").aj_addToView(self.view);
    titleLabel.font = SongKeFont(23);
    [titleLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.view).offset(20);
        make.top.equalTo(self.view).offset(STATUS_BAR_HEIGHT);
        make.height.equalTo(@44);
    }];
    self.navigationItem.titleView = titleLabel;
    
    UILabel * topLabel = [UILabel new];
    topLabel.aj_Text(@"记住你的Anything~").aj_textColorHexStr(@"#ffffff").aj_addToView(self.view);
    topLabel.font = SongKeFont(19);
    [topLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.view).offset(20);
        make.centerX.equalTo(self.view);
    }];
    
    UILabel * bottomLabel = [UILabel new];
    bottomLabel.aj_Text(@"万物记").aj_textColor([UIColor colorWithAjenHex:0xffffff alpha:0.3]).aj_addToView(self.view);
    bottomLabel.font = SongKeFont(60);
    [bottomLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.equalTo(self.view).offset(-40);
        make.centerX.equalTo(self.view);
    }];
    
    
    rightItem = [[UIBarButtonItem alloc] initWithTitle:@"编辑" style:UIBarButtonItemStylePlain target:self action:@selector(rightItemDown)];
    rightItem.tag = 200;
    rightItem.tintColor = [UIColor colorWithAjenHexString:@"#7a7374"];
    
    rightItem2 = [[UIBarButtonItem alloc] initWithTitle:@"新增" style:UIBarButtonItemStylePlain target:self action:@selector(addNewWordDown)];
    rightItem2.tintColor = [UIColor colorWithAjenHexString:@"#7a7374"];
    self.navigationItem.rightBarButtonItems= @[rightItem,rightItem2];
    
    
    [self.view addSubview:self.tableView];
    [self.tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(self.view);
    }];
}

-(void)rightItemDown{
    if(rightItem.tag == 200){
        rightItem = [[UIBarButtonItem alloc] initWithTitle:@"完成" style:UIBarButtonItemStylePlain target:self action:@selector(rightItemDown)];
        rightItem.tag = 100;
        self.navigationItem.rightBarButtonItems = @[rightItem];
        self.tableView.editing = YES;
    }else{
        rightItem = [[UIBarButtonItem alloc] initWithTitle:@"编辑" style:UIBarButtonItemStylePlain target:self action:@selector(rightItemDown)];
        rightItem.tag = 200;
        self.navigationItem.rightBarButtonItems= @[rightItem,rightItem2];
        self.tableView.editing = NO;
    }
    rightItem.tintColor = [UIColor colorWithAjenHexString:@"#7a7374"];
}

-(void)addNewWordDown{
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"新增词条" message:nil preferredStyle:UIAlertControllerStyleAlert];
    [alertController addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleDefault handler:nil]];
    [alertController addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        UITextField *textField = alertController.textFields.firstObject;
        NSArray * localTitleArray = [[NSUserDefaults standardUserDefaults] objectForKey:@"LOCAL_WORDS"];
        if([localTitleArray containsObject:textField.text]){
            [self showMsg:@"该栏目已存在,请更换栏目名字"];
        }else{
            isEdit = YES;
            [[LocalModel shared] addNewTabInLastWithTitle:textField.text];
            [self.tableView reloadData];
        }
    }]];
    [alertController addTextFieldWithConfigurationHandler:^(UITextField * _Nonnull textField) {
        textField.placeholder = @"请输入栏目名字";
    }];
    [self presentViewController:alertController animated:true completion:nil];
}


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return [LocalModel shared].model.Anything.count;
}

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return CGFLOAT_MIN;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return 20;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 65;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    static NSString *CellIdentifier =@"EditHomeTabCell";
    EditHomeTabCell *cell = [tableView  dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell ==nil){
        cell = [[EditHomeTabCell alloc]initWithStyle:UITableViewCellStyleSubtitle  reuseIdentifier:CellIdentifier];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
    }
    if([LocalModel shared].model.Anything.count){
        cell.nameLabel.text = [LocalModel shared].model.Anything[indexPath.row].tabTitle;
        if([LocalModel shared].model.Anything[indexPath.row].contentsList.count){
            cell.countLabel.text = [NSString stringWithFormat:@"└ 条数:%ld",[LocalModel shared].model.Anything[indexPath.row].contentsList.count];
        }else{
            cell.countLabel.text = [NSString stringWithFormat:@"└ 空"];
        }
    }
    return cell;
}


- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    if(rightItem.tag == 200){
        return NO;
    }else{
        return YES;
    }
}


-(void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)sourceIndexPath toIndexPath:(NSIndexPath *)destinationIndexPath{
    [[LocalModel shared]changeTabFromIndex:sourceIndexPath.row toIndex:destinationIndexPath.row];
    [self.tableView reloadData];
    isEdit = YES;
}
-(void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath{
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        if([LocalModel shared].model.Anything.count <= 1){
            ShowTextHUD(@"首页最低保留一个栏目");
        }else{
            [[LocalModel shared] removeTabWithIndes:indexPath.row];
            [self.tableView reloadData];
            isEdit = YES;
        }
        
    }
}

-(NSString*)tableView:(UITableView*)tableView titleForDeleteConfirmationButtonForRowAtIndexPath:(NSIndexPath*)indexpath {
    return @"删除该栏目";
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    NewChangeNicknameAlertView * changeNickNameView = [NewChangeNicknameAlertView new];
    changeNickNameView.normalNickName = [LocalModel shared].model.Anything[indexPath.row].tabTitle;
    [[UIApplication sharedApplication].keyWindow addSubview:changeNickNameView];
    [changeNickNameView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo([UIApplication sharedApplication].keyWindow);
    }];
    [UIView animateWithDuration:0.3 animations:^{
        changeNickNameView.backgroundColor = [UIColor colorWithAjenHex:0x000000 alpha:0.5];
    }];
    
    changeNickNameView.commitBlock = ^(NSString * _Nonnull nickName) {
        [[LocalModel shared] renameTabWithTitle:nickName andCurrentIndex:indexPath.row];
        [self.tableView reloadData];
        isEdit = YES;
    };
    
    changeNickNameView.alertStr = @"修改栏目名(15字以内)";
}

-(UITableView *)tableView{
    if(_tableView == nil){
        _tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, 0, 0) style:UITableViewStyleGrouped];
        _tableView.delegate =self;
        _tableView.dataSource=self;
        _tableView.showsVerticalScrollIndicator = NO;
        _tableView.separatorColor = [UIColor colorWithAjenHex:0x7a7374 alpha:0.2];
        _tableView.backgroundColor = [UIColor colorWithAjenHex:0xffffff alpha:0.9];
        if (@available(iOS 11.0, *)) {
            _tableView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
            _tableView.scrollIndicatorInsets = _tableView.contentInset;
        }
        _tableView.estimatedRowHeight = 0;
        _tableView.estimatedSectionHeaderHeight = 0;
        _tableView.estimatedSectionFooterHeight = 0;
        UIView *tableViewHeaderView = [[UIView alloc] initWithFrame:CGRectMake(0.0, 0.0, _tableView.bounds.size.width, CGFLOAT_MIN)];
        _tableView.tableHeaderView = tableViewHeaderView;
    }
    return _tableView;
}

-(void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    if(isEdit){
         [[NSNotificationCenter defaultCenter] postNotificationName:@"REFRESH_HOME_TAB" object:nil userInfo:@{@"isEdit":@"YES"}];
    }
}
@end
